import AMapLoader from '@amap/amap-jsapi-loader'
import { EQUIPMENT_LOCATIONS, PARK_BOUNDARY } from '@/config/map'

// 设备类型图标配置
const EQUIPMENT_ICONS = {
  air: '🌬️',
  water: '💧',
  noise: '🔊',
  treatment: '🏭'
}

const createMarkerContent = (equipment: any) => {
  return `
    <div class="marker-content" style="
      background: rgba(0,255,255,0.2);
      border: 1px solid #0ff;
      padding: 5px 10px;
      border-radius: 4px;
      color: #fff;
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 5px;
    ">
      <span style="font-size: 16px;">${EQUIPMENT_ICONS[equipment.type]}</span>
      <span>${equipment.name}</span>
      <span style="
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: ${equipment.status === 'normal' ? '#0f0' : '#f00'};
      "></span>
    </div>
  `
}

export const initMap = async (container: HTMLElement, config: any) => {
  try {
    const AMap = await AMapLoader.load({
      key: config.key,
      version: '2.0',
      plugins: [
        'AMap.Scale',
        'AMap.ToolBar',
        'AMap.MapType',
        'AMap.GeoJSON',
        'AMap.Polygon',
        'AMap.HawkEye',
        'AMap.ControlBar',
        'AMap.TileLayer.Satellite',
        'AMap.TileLayer.RoadNet'  // 添加路网图层插件
      ]
    })

    const map = new AMap.Map(container, {
      zoom: config.zoom,
      center: config.center,
      pitch: config.pitch,
      viewMode: '3D',
      mapStyle: 'amap://styles/dark',
      features: config.features,
      skyColor: config.skyColor,
      buildingAnimation: config.buildingAnimation
    })

    // 创建图层
    const satelliteLayer = new AMap.TileLayer.Satellite()
    const roadNetLayer = new AMap.TileLayer.RoadNet()
    const defaultLayer = new AMap.TileLayer({
      zooms: [3, 20],
      visible: true
    })

    // 扩展地图实例方法
    map.mapControl = {
      to2D: () => {
        map.setLayers([defaultLayer])
        map.setViewMode('2D')
        map.setPitch(0)
        map.setMapStyle('amap://styles/dark')
      },
      to3D: () => {
        map.setLayers([defaultLayer])
        map.setViewMode('3D')
        map.setPitch(45)
        map.setMapStyle('amap://styles/dark')
      },
      toSatellite: () => {
        map.setLayers([satelliteLayer, roadNetLayer])
      },
      toRoad: () => {
        map.setLayers([defaultLayer])
        map.setMapStyle('amap://styles/dark')
      }
    }

    // 添加 3D 控制插件
    const controlBar = new AMap.ControlBar({
      position: {
        right: '10px',
        top: '80px'
      }
    })
    map.addControl(controlBar)

    // 添加园区边界
    const parkBoundary = new AMap.Polygon({
      path: PARK_BOUNDARY,
      strokeColor: '#0ff',
      strokeWeight: 2,
      strokeOpacity: 0.8,
      fillColor: '#0ff',
      fillOpacity: 0.1,
      strokeStyle: 'dashed'
    })

    // 添加边界发光效果
    const glowLine = new AMap.Polygon({
      path: PARK_BOUNDARY,
      strokeColor: '#0ff',
      strokeWeight: 6,
      strokeOpacity: 0.2,
      fillColor: 'none',
      zIndex: 1
    })

    map.add([parkBoundary, glowLine])

    // 添加园区名称标记
    const parkLabel = new AMap.Text({
      text: config.parkName,
      position: config.center,
      style: {
        'padding': '5px 10px',
        'backgroundColor': 'rgba(0,255,255,0.1)',
        'borderRadius': '3px',
        'borderWidth': '1px',
        'borderColor': '#0ff',
        'color': '#fff',
        'fontSize': '12px',
        'fontWeight': 'bold'
      },
      offset: new AMap.Pixel(0, -20)
    })
    map.add(parkLabel)

    // 添加设备标记
    EQUIPMENT_LOCATIONS.forEach(equipment => {
      const markerContent = document.createElement('div')
      markerContent.innerHTML = createMarkerContent(equipment)

      const marker = new AMap.Marker({
        position: equipment.position,
        content: markerContent.firstElementChild,
        offset: new AMap.Pixel(-60, -15),
        anchor: 'bottom-center'
      })

      // 添加点击事件和信息窗体
      marker.on('click', () => {
        const info = new AMap.InfoWindow({
          content: `
            <div style="padding: 10px; background: rgba(0,0,0,0.8); border: 1px solid #0ff;">
              <h4 style="margin: 0 0 5px 0; color: #0ff;">${equipment.name}</h4>
              <p style="margin: 0; color: #fff;">
                状态: <span style="color: ${equipment.status === 'normal' ? '#0f0' : '#f00'}">
                  ${equipment.status === 'normal' ? '正常' : '警告'}
                </span>
              </p>
            </div>
          `,
          offset: new AMap.Pixel(0, -30),
          isCustom: true
        })
        info.open(map, equipment.position)
      })

      map.add(marker)
    })

    // 添加地图控件
    map.addControl(new AMap.Scale({
      position: 'LB'
    }))

    map.addControl(new AMap.ToolBar({
      position: 'RB'
    }))

    // 禁用默认的图层切换控件
    map.removeControl(map.getControl('MapType'))

    return map
  } catch (error) {
    console.error('地图初始化失败:', error)
    throw error  // 抛出错误以便在组件中捕获
  }
} 